<?php

namespace app\http;

use app\admin\model\Token;
use think\Db;
use think\facade\Env;
use think\facade\Request;

trait TokenTrait
{
    use GetUid;

    //生成token方法代码
    public function setToken()
    {
        // return base64_encode(random_bytes(32));//生成一个不会重复的字符串
        $cstrong = true;
        // var_dump(openssl_random_pseudo_bytes(32, $cstrong));
         return base64_encode(openssl_random_pseudo_bytes(32, $cstrong));
//        return self::makeToken();
    }

    protected static function makeToken()
    {
        try {
            $salt = random_int(1000000000000, 9999999999999);
        } catch (\Exception $e) {
            $salt = microtime(true);
        }
        return base64_encode(hash_hmac('haval256,4', $salt, self::getAppKey()));
    }

    //token验证
    public function checkToken($token)
    {
        $current = Token::where('token', $token)->find();
//        dump($current);
        if (!empty($current)) {
            if (time() - $current['out_time'] > 0) {
                return 90003;//token长时间未使用而过期，需重新登陆
            } else {
                return 90001;//token验证成功
            }
        } else {
            return 90002;//token错误验证失败
        }
    }

    protected static function getToken($uid)
    {
        return Token::where('uid', $uid)->find();
    }

    protected static function createToken($data)
    {
        return Token::create($data);
    }

    protected static function updateToken($uid, $data)
    {
        return Token::where('uid', $uid)->update($data);
    }

    protected static function getAppKey()
    {
        return Env::get('app_key', '$2y$10$NnkpUgVoK4LLtMd6xhJz3.bgcPHCC.3gHHDm6BaycHiCoB.mXAlTu');
    }
}
